<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>系统设置</title>
    <script src="/assets/tailwind.js"></script>
    <link href="/assets/fontawesome-free-6.7.2-web/css/all.min.css" rel="stylesheet">
    <script src="/assets/qrcode.min.js"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        secondary: '#4080FF',
                        success: '#00B42A',
                        warning: '#FF7D00',
                        danger: '#F53F3F',
                        dark: '#1D2129',
                        light: '#F2F3F5',
                    },
                    fontFamily: {
                        inter: ['Inter', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .bg-gradient-blue {
                background: linear-gradient(135deg, #165DFF 0%, #4080FF 100%);
            }
            .shadow-card {
                box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
            }
            .transition-all-300 {
                transition: all 0.3s ease;
            }
            .tab-active {
                @apply border-primary text-primary;
            }
            .table-row-hover {
                @apply hover:bg-gray-50 transition-all-300;
            }
        }
    </style>
</head>
<body class="bg-gray-50 font-inter text-dark min-h-screen flex flex-col">
    <!-- 顶部导航栏 -->
    <header class="bg-white shadow-sm sticky top-0 z-50">
        <div class="container mx-auto px-4 py-3 flex items-center justify-between">
            <div class="flex items-center space-x-2">
                <i class="fa fa-shield text-primary text-xl"></i>
                <h1 class="text-xl font-bold text-primary">管理员控制台</h1>
            </div>
            <nav class="hidden md:flex items-center space-x-6">
                <a href="." class="text-gray-600 hover:text-primary transition-all-300 flex items-center">
                    <i class="fa fa-tachometer mr-2"></i> 首页
                </a>
                <a href="qr" class="text-gray-600 hover:text-primary transition-all-300 flex items-center">
                    <i class="fa fa-cog mr-2"></i> 二维码
                </a>
                <a href="system-settings" class="text-primary font-medium flex items-center">
                    <i class="fa fa-cog mr-2"></i> 系统设置
                </a>
            </nav>
            <div class="flex items-center space-x-4">
                <a href="logs" class="text-gray-600 hover:text-primary transition-all duration-300 inline-block">
                    <i class="fa fa-bell text-xl"></i>
                </a>

                <button class="md:hidden text-gray-600 hover:text-primary transition-all-300">
                    <i class="fa fa-bars text-xl"></i>
                </button>
            </div>
        </div>
    </header>

    <!-- 主要内容区 -->
    <main class="flex-grow container mx-auto px-4 py-8">
        <div class="max-w-5xl mx-auto">
            <!-- 页面标题 -->
            <div class="mb-8">
                <h2 class="text-[clamp(1.5rem,3vw,2.5rem)] font-bold text-dark mb-2">系统设置</h2>
                <p class="text-gray-500">修改系统设置和二维码信息</p>
            </div>

            <!-- 系统设置卡片 -->
            <div class="bg-white rounded-xl shadow-card p-6 mb-8">
                <form id="system-form" class="space-y-6" action="/saveqr" method="POST">
                    <!-- 新增：设备IP选择下拉框和应用按钮 -->
                    <div class="space-y-2">
                        <label class="block text-sm font-medium text-gray-700">设备IP选择</label>
                        <div class="flex items-center space-x-4">
                            <!-- 设备IP下拉选择框 -->
                            <select id="device-ip-select" 
                                class="flex-1 px-4 py-3 rounded-lg border border-gray-300 focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all-300"
                                >
                                <option value="" disabled selected>请选择设备IP</option>
                                <!-- 示例IP：实际项目中可通过后端接口动态生成设备IP列表 -->
                                <!-- 动态生成的IP选项 -->
                                <!-- Tera循环语法 -->
                                {% for ip in ip_addresses %}
                                    <option value="{{ ip }}"> {{ ip }}</option>
                                {% endfor %}
                            </select>
                            <!-- 应用IP按钮 -->
                            <button type="button" id="apply-ip-btn"
                                class="px-6 py-3 bg-secondary text-white rounded-lg hover:bg-secondary/90 transition-all-300 flex items-center shadow-md hover:shadow-lg">
                                <i class="fa fa-check mr-2"></i> 应用IP
                            </button>
                        </div>
                        <p class="text-xs text-gray-500">选择设备IP后，二维码链接将自动生成为：http://[选中IP]:18516</p>
                    </div>
                    <div class="space-y-2">
                        <label for="qr_code_url" class="block text-sm font-medium text-gray-700">二维码链接</label>
                        <input type="text" id="qr_code_url" name="qr_code_url" value = "{{ qr_url }}"
                            class="w-full px-4 py-3 rounded-lg border border-gray-300 focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all-300"
                            placeholder="请输入二维码链接">
                    </div>
                    <div class="flex justify-end">
                        <button id="save-system-btn" class="px-6 py-3 bg-primary text-white rounded-lg hover:bg-primary/90 transition-all-300 flex items-center shadow-md hover:shadow-lg">
                            保存
                        </button>
                    </div>
                </form>
            </div>
            <div    id="qr-change-result" 
                    class="mt-4 flex items-center space-x-3 p-3 rounded-lg transition-all-300 {{ upload_result_color }}-100 border {{ upload_result_color }}-200 text-{{ upload_result_color }}-500"
                >
                    <span id="qr-change-text" class="flex-1">
                        {{ upload_result }}
                    </span>
            </div>
            <div id="messages" class="mb-6 hidden">
                <ul class="divide-y divide-gray-200 rounded-lg bg-white shadow-sm">
                    <!-- 消息将通过JavaScript动态添加 -->
                    {% for message in messages %}
                    <li>
                        <span><strong>{{ message }}</strong></span>
                    </li>
                    {% endfor %}
                </ul>
            </div>
            <!-- 操作结果提示 -->
            <div id="result-message" class="hidden p-4 rounded-lg mb-6 transition-all-300 transform translate-y-4 opacity-0">
                <div id="success-message" class="hidden bg-success/10 border border-success/20 text-success p-4 rounded-lg">
                    <div class="flex items-start">
                        <div class="flex-shrink-0 pt-0.5">
                            <i class="fa fa-check-circle text-xl"></i>
                        </div>
                        <div class="ml-3">
                            <h3 class="text-sm font-medium">操作成功</h3>
                            <div class="mt-2 text-sm">
                                <p id="success-text">操作已成功完成。</p>
                            </div>
                        </div>
                    </div>
                </div>
                <div id="error-message" class="hidden bg-danger/10 border border-danger/20 text-danger p-4 rounded-lg">
                    <div class="flex items-start">
                        <div class="flex-shrink-0 pt-0.5">
                            <i class="fa fa-exclamation-circle text-xl"></i>
                        </div>
                        <div class="ml-3">
                            <h3 class="text-sm font-medium">操作失败</h3>
                            <div class="mt-2 text-sm">
                                <p id="error-text">操作未能完成，请重试。</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </main>

    <!-- 页脚 -->
    <footer class="bg-white border-t border-gray-200 py-6">
        <div class="container mx-auto px-4">
            <div class="flex flex-col md:flex-row justify-between items-center">
                <div class="mb-4 md:mb-0">
                    <p class="text-gray-500 text-sm">&copy; 2025 北京椰子树信息技术有限公司. 保留所有权利.</p>
                </div>
                <div class="flex space-x-6">
                    <a href="http://www.coconet.cn" class="text-gray-500 hover:text-primary transition-all-300">
                        <i class="fa fa-question-circle mr-1"></i> 帮助中心
                    </a>
                    <a href="http://www.coconet.cn" class="text-gray-500 hover:text-primary transition-all-300">
                        <i class="fa fa-file-text-o mr-1"></i> 隐私政策
                    </a>
                    <a href="mailto:goodput3@qq.com" class="text-gray-500 hover:text-primary transition-all-300">
                        <i class="fa fa-phone mr-1"></i> 联系我们
                    </a>
                </div>
            </div>
        </div>
    </footer>

    <script>

        // 显示操作结果消息
        function showResultMessage(success, message) {
            const resultMessage = document.getElementById('result-message');
            const successMessage = document.getElementById('success-message');
            const errorMessage = document.getElementById('error-message');
            const successText = document.getElementById('success-text');
            const errorText = document.getElementById('error-text');

            resultMessage.classList.remove('hidden');
            resultMessage.classList.add('translate-y-0', 'opacity-100');

            if (success) {
                successMessage.classList.remove('hidden');
                errorMessage.classList.add('hidden');
                successText.textContent = message;
            } else {
                successMessage.classList.add('hidden');
                errorMessage.classList.remove('hidden');
                errorText.textContent = message;
            }

            setTimeout(() => {
                resultMessage.classList.add('translate-y-4', 'opacity-0');
                setTimeout(() => {
                    resultMessage.classList.add('hidden');
                }, 300);
            }, 3000);
        }

                // 显示消息
        function showMessages(messages, type) {
            const messagesContainer = document.getElementById('messages');
            const messagesList = document.querySelector('#messages ul');
            
            messages.forEach(message => {
                const li = document.createElement('li');
                li.className = 'px-4 py-3';
                
                if (type === 'error') {
                    li.className += ' bg-danger/10 text-danger';
                    li.innerHTML = `<span><strong><i class="fa fa-exclamation-circle mr-2"></i>${message}</strong></span>`;
                } else {
                    li.className += ' bg-success/10 text-success';
                    li.innerHTML = `<span><strong><i class="fa fa-check-circle mr-2"></i>${message}</strong></span>`;
                }
                
                messagesList.appendChild(li);
            });
            
            messagesContainer.classList.remove('hidden');
            
            if (type === 'error') {
                setTimeout(() => {
                    messagesContainer.classList.add('hidden');
                    messagesList.innerHTML = '';
                }, 3000);
            }
        }
        // 获取元素
        const resultElement = document.getElementById('qr-change-result');

        // 示例：修改内容和颜色
        function updateResult(success, message) {
            // 设置文本内容
            resultElement.textContent = message;
            
            // 根据成功状态修改颜色类名
            const colorClass = success ? 'green' : 'red';
            resultElement.className = resultElement.className
            .split(' ')
            .filter(cls => !cls.startsWith('text-')) // 移除旧颜色类
            .join(' ') + ` text-${colorClass}-500 mt-4`; // 添加新颜色类
        }
        const dropdownBtn = document.getElementById('adminDropdownBtn');
        const dropdownMenu = document.getElementById('adminDropdownMenu');
      
      
        // 点击外部关闭菜单
        window.addEventListener('click', (event) => {
          if (!event.target.closest('#adminDropdownBtn, #adminDropdownMenu')) {
            dropdownMenu.classList.add('hidden');
            dropdownBtn.querySelector('.fa-angle-down').classList.remove('rotate-180');
          }
        });
        // 目录选择相关函数（仅更新输入框，不提交表单）
        function triggerDirectorySelection() {
            //不要触发提交表格
            event.preventDefault();
            document.getElementById('directory-input').click();
        }

        function handleDirectorySelect(input) {
            if (input.files && input.files[0]) {
                // 非标准路径获取方式（仅部分浏览器支持）
                const directoryPath = input.files[0].path || '未选择目录';
                console.log('Selected directory:', directoryPath);
                document.getElementById('http-root').value = directoryPath;
            }
        }

    // ==============================================
    // MODIFIED: 点击"应用IP"时自动更新QR URL并提交表单（触发保存）
    // ==============================================
    document.addEventListener('DOMContentLoaded', () => {
        // 获取关键元素
        const ipSelect = document.getElementById('device-ip-select'); // IP下拉框
        const applyIpBtn = document.getElementById('apply-ip-btn'); // 应用IP按钮
        const qrUrlInput = document.getElementById('qr_code_url'); // QR URL输入框
        const systemForm = document.getElementById('system-form'); // 系统设置表单（用于提交保存）

        // 给"应用IP"按钮绑定点击事件
        applyIpBtn.addEventListener('click', () => {
            // Step 1: 验证是否选择了IP
            const selectedIp = ipSelect.value;
            if (!selectedIp) {
                showResultMessage(false, '请先从下拉框选择设备IP');
                updateResult(false, '请选择设备IP后再应用');
                return; // 未选IP时终止操作
            }

            // Step 2: 生成对应的QR URL（格式：http://[选中IP]:18516）
            const qrUrl = `http://${selectedIp}:18516`;
            qrUrlInput.value = qrUrl; // 更新输入框内容

            // Step 3: 自动提交表单（等价于点击"保存"按钮）
            systemForm.submit();

            // Step 4: 显示反馈（可选，增强用户体验）
            showResultMessage(true, `IP已应用，正在保存QR链接: ${qrUrl}`);
            updateResult(true, `IP应用成功，已自动保存QR链接`);
        });
    });

    </script>
</body>
</html>
